<template>
  <div v-if="configIdFlag">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/config' }">
          <i class="el-icon-lx-cascades"></i> AI模型配置列表
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 配置详情
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

<!--  <el-tab-pane :label="featureList"> </el-tab-pane>-->
      <div class="container">
        <div class="form-box" >
          <el-form ref="formRef" label-width="100px" label-position="left">
            <el-form-item label="学习类型：" >
              <div v-if="config.learningType === 'SUPERVISED_LEARNING'">
                监督学习
              </div>
              <div v-else-if="config.learningType === 'UNSUPERVISED_LEARNING'">
                非监督学习
              </div>
            </el-form-item>
            <el-form-item label="特征字段:" >
              {{config.features}}
            </el-form-item>
            <el-form-item label="目标字段:" >
              {{config.label}}
            </el-form-item>

            <el-form-item label="模型列表:" >
            <el-table :data="modelData" border class="table" ref="fieldTable" header-cell-class-name="table-header" @selection-change="handleSelectChange">
              <el-table-column label="模型名" width="150%">
                <template #default="scope"><span>{{ scope.row.modelName }}</span></template>
              </el-table-column>
              <el-table-column label="机器学习算法" width="150%">
                <template #default="scope">
                  {{handleAlgorithmName(scope.row.machineLearningAlgorithm)}}
                </template>
              </el-table-column>
              <el-table-column label="训练状态">
                <template #default="scope" >
                  <div v-if="scope.row.trainingState==='WAITING'">未训练</div>
                  <div v-else-if="scope.row.trainingState==='ON_GOING'">训练中</div>
                  <div v-else-if="scope.row.trainingState==='SUCCESS'">训练成功</div>
                  <div v-else="">训练失败</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" align="center">
                <template #default="scope">
                  <router-link :to="{path:'/modelList',query:{modelId:scope.row.id}}">
                    <el-button type="text" >查看模型
                    </el-button>
                  </router-link>
                </template>
              </el-table-column>
            </el-table>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"  @click="createModel()">生成模型</el-button>
            </el-form-item>
          </el-form>

          <el-dialog title="新建模型" v-model="modelVisiable" width="30%">
            <el-form label-width="120px">
              <el-form-item label="模型名称" required>
                <el-input v-model="form.modelName"></el-input>
              </el-form-item>
              <el-form-item label="选择算法" required>
                <el-select
                    v-model="form.machineLearningAlgorithm"
                    placeholder="请选择一个算法"
                    value-key="self"
                >
                  <el-option
                      v-for="(item,index) in enumList"
                      :key="index"
                      :label="item.algorithmName"
                      :value="item"
                  />
                </el-select>
              </el-form-item>
                <div v-for="(item,index) in form.machineLearningAlgorithm.trainParamEnums" :key="index">
                  <el-tooltip placement="left-start" >
                    <template #content>
                      描述：{{item.descriptionZH}}<br/>
                      类型：{{item.paramType}}<br/>
                      范围：{{item.leftBound}}~{{item.rightBound}}
                    </template>
                    <el-form-item :label="item.paramNameZH">
                      <el-input v-model="form.trainParams[index]" ></el-input>
                    </el-form-item>

                  </el-tooltip>
                </div>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="modelVisiable = false" size="medium">再想想</el-button>
                    <el-button type="primary" @click="saveModel" size="medium">确定</el-button>
                </span>
            </template>
          </el-dialog>
          </div>
        </div>
<!--      <div class="pagination">-->
<!--        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"-->
<!--                       :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>-->
<!--      </div>-->

    </div>





</template>

<script>
import {ref, reactive, getCurrentInstance, onMounted} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { fetchData } from "../../api";
import {getFileDetail} from "../../api/file";
import {getOneConfig} from "../../api/config";
import {useRoute}from "vue-router";
import {addModel, getModelByConfigId} from "../../api/model";
import {getEnum} from "../../api/utils";
export default {
  name: "configDetail",
  //训练特征
  setup() {
    const query = reactive({
      address: "",
      name: "",
      pageIndex: 1,
      pageSize: 10,
    });
    const fileId=ref(1);
    const tableData = ref([]);
    const selectData = ref([]);
    const pageTotal = ref(0);
    const modelData=ref([]);
    const config=ref([]);
    const route=useRoute()
    const showMaxIter=ref(false);
    const showRegParam=ref(false);
    const showElasticNetParam=ref(false);
    const showCategory=ref(false);
    const showTrainingDataSetOccupy=ref(false);
    const showNumOfCluster=ref(false);
    const showSeed=ref(false);
    let configId=route.query.configId;
    let configIdFlag = ref(false);

    let enumList = ref([])

    let form = reactive({
      configId: route.query.configId,
      modelName: "",
      machineLearningAlgorithm: '',
      trainParams: [],
    });
    // 获取表格数据

    const getData = () => {
      if(route.query.configId!=='') {
        const payload ={
          configId: route.query.configId,
          userId: localStorage.getItem("ms_userId")
        }
        getOneConfig(payload).then(res => {
          if (configId === '0') {
            configIdFlag.value = true;
            config.value={
              learningType: "SUPERVISED_LEARNING",
              features:{
                0:"模板字段1",
                1:"模板字段2"
              },
              label:"模板字段2"
            }
            console.log(config.value)
          } else if (res.msg === "成功") {
            configIdFlag.value = true;
            console.log(res.result)
            config.value=res.result;
            tableData.value = res.result.features;
            getEnum().then(resEnum=>{
              if (res.result.learningType === 'SUPERVISED_LEARNING'){
                const tempArr = resEnum.result[0]
                for (let j =0; j<tempArr.machineLearningAlgorithmTypeEnum.length;j++){
                  for (let k =0; k<tempArr.machineLearningAlgorithmTypeEnum[j].machineLearningAlgorithmEnums.length;k++){
                    enumList.value.push(tempArr.machineLearningAlgorithmTypeEnum[j].machineLearningAlgorithmEnums[k])
                  }
                }
              }
              else {
                const tempArr = resEnum.result[1]
                for (let j =0; j<tempArr.machineLearningAlgorithmTypeEnum.length;j++){
                  for (let k =0; k<tempArr.machineLearningAlgorithmTypeEnum[j].machineLearningAlgorithmEnums.length;k++){
                    enumList.value.push(tempArr.machineLearningAlgorithmTypeEnum[j].machineLearningAlgorithmEnums[k])
                  }
                }
              }
            })
          }
        })
        const payloadModel={
          configId:route.query.configId,
          userId: localStorage.getItem("ms_userId")
        }
        getModelByConfigId(payloadModel).then(res =>{
          modelData.value=res.result;
        })
      }
    };
    getData();

    const judgeAlgorithmType =()=>{
      if (form.machineLearningAlgorithm === 'LOGISTIC_REGRESSION_CLASSIFICATION') return 1;
      else if (form.machineLearningAlgorithm === 'K_MEANS_CLUSTERING') return 2;
      else return 3;
    }

    // 查询操作
    const handleSearch = () => {
      query.pageIndex = 1;
      getData();
    };
    // 分页导航
    const handlePageChange = (val) => {
      query.pageIndex = val;
      getData();
    };

    // 删除操作

    // 表格编辑时弹窗和保存
    const editVisible = ref(true);

    const saveModel = () => {
      modelVisiable.value = false
      const payload={
        configId:form.configId,
        userId: localStorage.getItem("ms_userId"),
        modelName:form.modelName,
        machineLearningAlgorithm: form.machineLearningAlgorithm.self,
        trainParams:{}
      }
      console.log(form.trainParams)
      let key_arr=[]
      let l = form.machineLearningAlgorithm.trainParamEnums.length
      for (let i = 0;i<l;i++){
          key_arr.push(form.machineLearningAlgorithm.trainParamEnums[i].self)
      }
      let param_obj={}
      for (let i=0;i<l;i++){
        let temp = key_arr[i]
        param_obj[temp]=form.trainParams[i]
      }
      payload.trainParams = param_obj
      console.log("payload"+JSON.stringify(payload))

      addModel(payload).then(res=>{
        console.log(res)
        if(res.msg === '成功') {
          ElMessage.success(`已成功生成模型`);
          getData()
        }
        else ElMessage.error(res.msg);
      }).catch(()=>{
        ElMessage.error( `生成模型失败`);
       }
      )


    };
    const handleEdit = () => {
      editVisible.value = true;
    };



    //生成模型弹窗
    const modelVisiable=ref(false);

    const createModel=()=>{
        modelVisiable.value=true;
    }
    const handleSelectChange=val=>{
      selectData.value=val;
    }

    const handleAlgorithmName=(name)=>{
      if (name === "DECISION_TREE_CLASSIFICATION") {
        return "决策树分类";
      } else if (name === "GRADIENT_BOOSTED_TREE_CLASSIFICATION") {
        return "梯度提升树分类";
      } else if (name === "LOGISTIC_REGRESSION_CLASSIFICATION") {
        return "对数几率回归分类";
      } else if (name === "MULTILAYER_PERCEPTRON_CLASSIFICATION") {
        return "多层感知器分类";
      } else if (name === "NAIVE_BAYES_CLASSIFICATION") {
        return "朴素贝叶斯分类";
      } else if (name === "XGBOOST_CLASSIFICATION") {
        return "XGBOOST分类";
      } else if (name === "RANDOM_FOREST_CLASSIFICATION") {
        return "随机森林分类";
      } else if (name === "K_MEANS_CLUSTERING") {
        return "K均值聚类";
      } else if (name === "DECISION_TREE_REGRESSION") {
        return "决策树回归算法";
      } else if (name === "RANDOM_FOREST_REGRESSION") {
        return "随机森林回归";
      }
    }

    return {
      modelVisiable,
      config,
      query,
      tableData,
      pageTotal,
      modelData,
      editVisible,
      form,
      fileId,
      configId,
      configIdFlag,
      showMaxIter,
      enumList,
      saveModel,

      showRegParam,
      showElasticNetParam,
      showCategory,
      showNumOfCluster,
      showSeed,
      showTrainingDataSetOccupy,

      judgeAlgorithmType,
      selectData,
      handleSelectChange,
      handleSearch,
      handlePageChange,
      createModel,
      handleEdit,

      handleAlgorithmName
    };
  },
};


</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}
.handle-table{
  margin-bottem: 40px;
}

.handle-select {
  width: 150px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
